﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MidApp
{
    public class ManageMessage
    {
        /// <summary>
        ///Metoda vytvori novou zpravu k tematu
        /// </summary>
        public static void CreateNewMessage(AppLib.Message NewMessage, int ThreadID)
        {
            var db = MidApp.LinqUse.DBConn;

            db.Messages.InsertOnSubmit(NewMessage);
            db.SubmitChanges();

            MidApp.ManageMessageBelongsToTopic.AssignMessageToTopic(ThreadID, NewMessage.MessageID);
        }
        /// <summary>
        ///Metoda edituje zpravu
        /// </summary>
        public static void EditMessage(AppLib.Message MessageToEdit)
        {
            var db = MidApp.LinqUse.DBConn;
            var oldMessage = (from Message in db.Messages where Message.MessageID == MessageToEdit.MessageID select Message).First();

            oldMessage.Report = MessageToEdit.Report;
            db.SubmitChanges();
        }
        /// <summary>
        ///Metoda vraci zpravy daneho tematu.
        /// </summary>
        public static List<AppLib.Message> GetMessagesAssignedToTopic(int ThreadID)
        {
            var db = MidApp.LinqUse.DBConn;
            
            var messages = (from Message in db.Messages join Belong in db.MessageBelongsToTopics on Message.MessageID equals Belong.MessageID where Belong.ThreadID == ThreadID orderby Message.Inserted descending select Message).ToList();

            return messages;
        }
        /// <summary>
        ///Metoda vraci zpravu.
        /// </summary>
        public static AppLib.Message GetMessage(int ThreadID, int MessageID)
        {
            var db = MidApp.LinqUse.DBConn;

            var message = (from Message in db.Messages join Belong in db.MessageBelongsToTopics on Message.MessageID equals Belong.MessageID where Belong.ThreadID == ThreadID && Belong.MessageID == MessageID select Message).First();

            return message;
        }
    }
}
